package cn.islu.service.impl;

import cn.islu.bean.TbMusic;
import cn.islu.dao.TbMusicDao;
import cn.islu.service.TbMusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TbMusicServiceImpl implements TbMusicService {
    @Autowired
    private TbMusicDao tbMusicDao;

    @Override
    public List<TbMusic> findAll() {
        return tbMusicDao.findAll();
    }

    @Override
    public TbMusic findById(Integer musicId) {
        return tbMusicDao.findById(musicId);
    }

    @Override
    public TbMusic prevSong(Integer musicId) {
        List<TbMusic> list = tbMusicDao.findAll();
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            if (musicId.equals(list.get(i).getMusicId())) {
                index = i;
                break;
            }
        }
        index = index == 0 ? list.size() - 1 : index - 1;
        return list.get(index);
    }

    @Override
    public TbMusic nextSong(Integer musicId) {
        List<TbMusic> list = tbMusicDao.findAll();
        int index = 0;
        for (int i = 0; i <list.size() ; i++) {
            if (musicId.equals(list.get(i).getMusicId())){
                index = i;
                break;
            }
        }
        index = index==list.size()-1? 0:index+1;
        return list.get(index);
    }

    @Override
    public List<TbMusic> search(String keyword) {
       keyword = "%" + keyword + "%";
        List<TbMusic> list = tbMusicDao.likeByName(keyword);
        List<TbMusic> list1 = tbMusicDao.likeByArtistName(keyword);
        List<TbMusic> list2 = tbMusicDao.likeByAlbumName(keyword);

        list1.addAll(list2);
        list.addAll(list1);

        LinkedHashSet<TbMusic> musics = new LinkedHashSet<>(list);
        list = new ArrayList<>(musics);
        return list;
    }
}
